package com.fishbone.secure.support;

import com.fishbone.common.utils.FastJsonUtil;
import com.fishbone.secure.entity.Claims;
import com.fishbone.secure.entity.Principal;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * @ClassName SecurityContextHolder
 * @Author huyaxi
 * @DATE 2020/6/11 10:23
 */
public class CurrentUserContextHolder {

    private static final String ANONYMOUS_USER = "anonymousUser";

    private static Claims getClaims() {
        Object object = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if(!ANONYMOUS_USER.equals(object) && Objects.nonNull(object)){
            String principalStr = FastJsonUtil.toJSONString(object);
            Principal principal = FastJsonUtil.toBean(principalStr,Principal.class);
            return principal.getClaims();
        }
        return null;
    }


    /**
     * 获取当前登录用户ID
     * @return
     */
    public static Long getUserId(){
        return Objects.nonNull(getClaims())?getClaims().getUserId():null;
    }


    public static List<Long> getRoleIds() {
        return Objects.nonNull(getClaims())?getClaims().getRoleIds(): Collections.emptyList();
    }

    public static List<String> getAuthorities() {
        return Objects.nonNull(getClaims())?getClaims().getAuthorities(): Collections.emptyList();
    }

    /**
     * 获取当前登录用户账号
     * @return
     */
    public static String getAccount() {
        return Objects.nonNull(getClaims())?getClaims().getAccount(): null;
    }


    /**
     * 获取当前登录用户的租户ID
     * @return
     */
    public static String getTenantId(){
        return Objects.nonNull(getClaims())?getClaims().getTenantId(): null;
    }


    /**
     * 获取当前登录用户的客户端ID
     * @return
     */
    public static String getClientId(){
        return Objects.nonNull(getClaims())?getClaims().getClient_Id(): null;
    }


    /**
     * 获取用户手机号码
     * @return
     */
    public static String getPhone() {
        return Objects.nonNull(getClaims())?getClaims().getPhone(): null;
    }

}
